package com.yonyou.gmcc.gateway.wechat.controller.message;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.marketing.common.entity.Check;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CookieSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.expression.ParseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.yonyou.gmcc.gateway.wechat.service.interfaces.ProviderValidateToWechatServiceInterface;
import com.yonyou.gmcc.gateway.wechat.service.interfaces.SendMessageDoingServiceInterface;
import com.yonyou.gmcc.gateway.wechat.service.interfaces.WechatApiServiceInterface;
import com.yonyou.gmcc.gateway.wechat.util.CookieUtil;
import com.yonyou.gmcc.gateway.wechat.util.CryptoTools;
import com.yonyou.gmcc.gateway.wechat.util.Md5Utils;
import com.yonyou.gmcc.gateway.wechat.util.TokenCheck;

import net.sf.json.JSONObject;

@Controller
// @RequestMapping(value = ApiVersionConsts.BASE_PATH )
public class WechatMessageDoingController {

	private static Logger logger = Logger.getLogger(WechatMessageDoingController.class);
	@Autowired
	private ProviderValidateToWechatServiceInterface validateService;

	@Autowired
	private SendMessageDoingServiceInterface sendMessageDoingService;

	@Autowired
	private WechatApiServiceInterface wechatApiService;
	@Autowired
	private Environment env;
	@Autowired
	private TokenCheck tokenCheck;

	@RequestMapping("/portalredirect/{id}")
	public String portalredirect(@PathVariable("id") String id) {
		logger.info("----------------portalredirect");
		String dm = env.getProperty("wechat.domain");
		String appid = env.getProperty("wechat.appid");
		String u = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://" + dm
				+ "/wx/portal/" + id + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		return "redirect:" + u;
	}

	@RequestMapping("/portal/{id}")
	public String portal(@PathVariable("id") String id, HttpServletRequest request) throws Exception {
		String code = request.getParameter("code");
		logger.info("获取到的Code为>>>>>>>" + code);
		String value = CookieUtil.getOpenid(request);
		logger.info("获取到的OPENID为>>>>>>>" + value);
		logger.info("----------------portal");
		String dm = env.getProperty("wechat.domain");
		long time = (new Date()).getTime();
		if(CheckUtil.NullOrEmpty(value)){
			if (id.equals("act")) {
				logger.info("进入资讯页面");
				return "redirect:http://" + dm + "/wx/views/act.html?t=" + time;
			} else if (id.equals("actes")) {
				return "redirect:http://" + dm + "/wx/views/actes.html?t=" + time;
			} else if (id.equals("sy")) {
				return "redirect:http://" + dm + "/wx/views/sy.html?t=" + time;
			} else if (id.equals("myAct")) {
				return "redirect:http://" + dm + "/wx/views/myAct.html?t=" + time;
			} else if (id.equals("servicehall")) {
				return "redirect:http://" + dm + "/wx/views/fp.html?t=" + time;
			} else if (id.equals("sendgift")) {
				return "redirect:http://" + dm + "/wx/views/td.html?t=" + time;
			} else if (id.equals("maintainbook")) {
				return "redirect:http://" + dm + "/wx/views/mt.html?t=" + time;
			} else if (id.equals("modules")) {
				return "redirect:http://" + dm + "/wx/views/modules/shopping.html?t=" + time;
			} else if (id.equals("violation")) {
				return "redirect:http://" + dm + "/wx/views/modules/violation.html?t=" + time;
			} else if (id.equals("roadSOS")) {
				return "redirect:http://" + dm + "/wx/views/modules/rescue.html?t=" + time;
			} else if (id.equals("parts")) {
				return "redirect:http://" + dm + "/wx/views/modules/parts.html?t=" + time;
			} else if (id.equals("information")) {
				return "redirect:http://" + dm + "/wx/views/modules/information.html?t=" + time;
			} else if (id.equals("hy")) {
				return "redirect:http://gmmc-wechat.bjscfl.com/index.php?g=Game&m=SlyderAdventures&a=index&openid=2B38PPlZLP8Jb9PNYKuHOSE7i0pvQhBwQ4+3D11";
			} else if (id.equals("knowledge")) {
				return "redirect:http://" + dm + "/wx/views/modules/knowledge.html?t=" + time;
			} else if (id.equals("take")) {
				return "redirect:http://" + dm + "/wx/views/modules/take.html?t=" + time;
			} else if (id.equals("forum")) {
				return "redirect:http://" + dm + "/wx/views/modules/forum.html?t=" + time;
			} else if (id.equals("drive")) {
				logger.info("进入试驾页面");
				return "redirect:http://" + dm + "/wx/pub/drive";
			} else if (id.equals("showroom")) {
				logger.info("进入车型展厅页面");
				return "redirect:http://" + dm + "/wx/pub/displayhall";
			} else if (id.equals("personal")) {
				logger.info("进入个人中心页面");
				return "redirect:http://" + dm + "/wx/pub/personal";
			} else {
				return "redirect:http://" + dm + "/wx/views/" + id + ".html?t=" + time;
			}
		}else{
			if (id.equals("act")) {
				logger.info("进入资讯页面");
				return "redirect:http://" + dm + "/wx/views/act.html?t=" + time;
			} else if (id.equals("actes")) {
				return "redirect:http://" + dm + "/wx/views/actes.html?t=" + time;
			} else if (id.equals("sy")) {
				return "redirect:http://" + dm + "/wx/views/sy.html?t=" + time;
			} else if (id.equals("myAct")) {
				return "redirect:http://" + dm + "/wx/views/myAct.html?t=" + time;
			} else if (id.equals("servicehall")) {
				return "redirect:http://" + dm + "/wx/views/fp.html?t=" + time;
			} else if (id.equals("sendgift")) {
				return "redirect:http://" + dm + "/wx/views/td.html?t=" + time;
			} else if (id.equals("maintainbook")) {
				return "redirect:http://" + dm + "/wx/views/mt.html?t=" + time;
			} else if (id.equals("modules")) {
				return "redirect:http://" + dm + "/wx/views/modules/shopping.html?t=" + time;
			} else if (id.equals("violation")) {
				return "redirect:http://" + dm + "/wx/views/modules/violation.html?t=" + time;
			} else if (id.equals("roadSOS")) {
				return "redirect:http://" + dm + "/wx/views/modules/rescue.html?t=" + time;
			} else if (id.equals("parts")) {
				return "redirect:http://" + dm + "/wx/views/modules/parts.html?t=" + time;
			} else if (id.equals("information")) {
				return "redirect:http://" + dm + "/wx/views/modules/information.html?t=" + time;
			} else if (id.equals("hy")) {
				return "redirect:http://gmmc-wechat.bjscfl.com/index.php?g=Game&m=SlyderAdventures&a=index&openid=2B38PPlZLP8Jb9PNYKuHOSE7i0pvQhBwQ4+3D11";
			} else if (id.equals("knowledge")) {
				return "redirect:http://" + dm + "/wx/views/modules/knowledge.html?t=" + time;
			} else if (id.equals("take")) {
				return "redirect:http://" + dm + "/wx/views/modules/take.html?t=" + time;
			} else if (id.equals("forum")) {
				return "redirect:http://" + dm + "/wx/views/modules/forum.html?t=" + time;
			} else if (id.equals("drive")) {
				logger.info("进入试驾页面");
				return "redirect:http://" + dm + "/wx/pub/drive?openId=" + value;
			} else if (id.equals("showroom")) {
				logger.info("进入车型展厅页面");
				return "redirect:http://" + dm + "/wx/pub/displayhall?openId=" + value;
			} else if (id.equals("personal")) {
				logger.info("进入个人中心页面");
				return "redirect:http://" + dm + "/wx/pub/personal?openId=" + value;
			} else {
				return "redirect:http://" + dm + "/wx/views/" + id + ".html?t=" + time;
			}
		}
	}

	@RequestMapping("/person")
	public String indexs1() {
		logger.info("----------------person");
		return "redirect:http://wxtest.gmmc.com.cn/wx/views/hpp.html";
	}

	@RequestMapping("/personredirect")
	public String personredirect() {
		logger.info("----------------personredirect");
		String u = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb85ed633e428bafc&redirect_uri=http://wxtest.gmmc.com.cn/wx/person&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		return "redirect:" + u;
	}

	@RequestMapping("/act")
	public String act() {
		logger.info("----------------act");
		return "redirect:http://wxtest.gmmc.com.cn/wx/views/act.html";
	}

	@RequestMapping("/actredirect")
	public String actredirect() {
		logger.info("----------------actredirect");
		String u = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb85ed633e428bafc&redirect_uri=http://wxtest.gmmc.com.cn/wx/act&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		return "redirect:" + u;
	}

	@RequestMapping("/sy")
	public String sy() {
		logger.info("----------------sy");
		return "redirect:http://wxtest.gmmc.com.cn/wx/views/sy.html";
	}

	@RequestMapping("/syredirect")
	public String syredirect() {
		logger.info("----------------syredirect");
		String u = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb85ed633e428bafc&redirect_uri=http://wxtest.gmmc.com.cn/wx/sy&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		return "redirect:" + u;
	}

	@RequestMapping("/myAct")
	public String myAct() {
		logger.info("----------------myAct");
		return "redirect:http://wxtest.gmmc.com.cn/wx/views/myAct.html";
	}

	@RequestMapping("/myActredirect")
	public String myActredirect() {
		logger.info("----------------myActredirect");
		String u = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb85ed633e428bafc&redirect_uri=http://wxtest.gmmc.com.cn/wx/myAct&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		return "redirect:" + u;
	}

	@RequestMapping("/servicehall")
	public String servicehall() {
		logger.info("----------------servicehall");
		return "redirect:http://wxtest.gmmc.com.cn/wx/views/fp.html";
	}

	@RequestMapping("/servicehallredirect")
	public String servicehallredirect() {
		logger.info("----------------servicehallredirect");
		String u = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb85ed633e428bafc&redirect_uri=http://wxtest.gmmc.com.cn/wx/servicehall&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		return "redirect:" + u;
	}

	@RequestMapping("/sendgift")
	public String sendgift() {
		logger.info("----------------sendgift");
		return "redirect:http://wxtest.gmmc.com.cn/wx/views/td.html";
	}

	@RequestMapping("/sendgiftredirect")
	public String sendgiftredirect() {
		logger.info("----------------sendgiftredirect");
		String u = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb85ed633e428bafc&redirect_uri=http://wxtest.gmmc.com.cn/wx/sendgift&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		return "redirect:" + u;
	}

	@RequestMapping("/maintainbook")
	public String maintainbook() {
		logger.info("----------------maintainbook");
		return "redirect:http://wxtest.gmmc.com.cn/wx/views/mt.html";
	}

	@RequestMapping("/maintainbookredirect")
	public String maintainbookredirect() {
		logger.info("----------------maintainbookredirect");
		String u = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb85ed633e428bafc&redirect_uri=http://wxtest.gmmc.com.cn/wx/maintainbook&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		return "redirect:" + u;
	}

	@RequestMapping(value = "/sharepage/getToken", method = RequestMethod.GET) // ,
																				// produces="text/html;charset=UTF-8"
	@ResponseBody
	public String getToken() {
		String token = wechatApiService.getToken();
		return token;
	}

	@RequestMapping(value = "/sharepage/getTicket", method = RequestMethod.GET) // ,
																				// produces="text/html;charset=UTF-8"
	@ResponseBody
	public String getTicket() {
		String token = getToken();
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
		try {
			String str = getReturnData(url);
			logger.info(str);
			JSONObject jsonObject = JSONObject.fromObject(str);
			String ticket = jsonObject.getString("ticket");
			logger.info("ticket为：" + ticket);
			return ticket;
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}

	public String getReturnData(String urlString) throws UnsupportedEncodingException {
		String res = "";
		try {
			URL url = new URL(urlString);
			java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			java.io.BufferedReader in = new java.io.BufferedReader(
					new java.io.InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				res += line;
			}
			in.close();
		} catch (Exception e) {
			logger.error("error in wapaction,and e is " + e.getMessage());
		}
		return res;
	}

	// 微信回调接口 /{wxToken}
	// @RequestMapping(value = "/wechatcall/request", method =
	// RequestMethod.GET)//, produces="text/html;charset=UTF-8"
	// @ResponseBody //@PathVariable("wxToken") String wxToken,
	public String validateGet(Check tokenModel, HttpServletRequest req,
			// @RequestBody String body,
			HttpServletResponse res) throws ParseException, IOException {
		logger.info("----TokenController,get,check");
		Enumeration<String> s = req.getParameterNames();
		while (s.hasMoreElements()) {
			String k = s.nextElement();
			logger.info(k);
			logger.info(req.getParameter(k));
		}
		String validate = validate("yycloud123", tokenModel);
		logger.info("---" + validate);
		return validate;
	}

	// 微信回调接口 /{wxToken}
	// @RequestMapping(value = "/wechatcall/request", method =
	// RequestMethod.POST)//, produces="text/html;charset=UTF-8"
	// @ResponseBody //@PathVariable("wxToken") String wxToken, Check
	// tokenModel,
	public String validatePost(HttpServletRequest req, HttpServletResponse res) {

		logger.info("----TokenController,post,check");
		Enumeration<String> s = req.getAttributeNames();
		while (s.hasMoreElements()) {
			logger.info(s.nextElement());
		}
		return "";
	}

	public String validate(String wxToken, Check tokenModel) {
		String signature = tokenModel.getSignature();
		Long timestamp = tokenModel.getTimestamp();
		Long nonce = tokenModel.getNonce();
		String echostr = tokenModel.getEchostr();
		if (signature != null && timestamp != null && nonce != null) {
			String[] str = { wxToken, timestamp + "", nonce + "" };
			Arrays.sort(str); // 字典序排序
			String bigStr = str[0] + str[1] + str[2];
			// SHA1加密
			String digest = Md5Utils.encode("SHA1", bigStr).toLowerCase();
			// 确认请求来至微信
			if (digest.equals(signature)) {
				return echostr;
			}
		}
		return "error";
	}

	// 主动发送文本消息
	@RequestMapping(value = "/sendTxtMessage", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sendTxtMessage(HttpServletRequest req, HttpServletResponse res) {
		try {
			logger.info("---------------sendTxtMessage controller,");
			String s = sendMessageDoingService.sendTxtMessage("oVX1SwE79SC_mCNFyIffOWqKSCFc", "send you message!");

			sendMessageDoingService.sendTxtMessage("oVX1SwPQCNc--NMMY1rhS5FLUub0", "send you message!");

			return s;

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return "error";
		}
	}

	@HystrixCommand(groupKey = "wechatService", fallbackMethod = "fallback2")
	@RequestMapping("/helloList")
	public @ResponseBody Map<String, String> indexList() {

		logger.info("------------------indexList,");
		Map<String, String> map = new HashMap<>();
		Check model = new Check();
		model.setEchostr("aaabb");
		map = validateService.indexList("abcd", model);// "", null
		return map;
	}

	@HystrixCommand(groupKey = "wechatService", fallbackMethod = "fallback3")
	@RequestMapping("/helloDto")
	public @ResponseBody Map<String, Object> indexDto() {

		Check model = new Check();
		model.setEchostr("aaabb");
		return validateService.indexDto("abcd");
	}

	@RequestMapping("/genToken")
	public String genToken() {
		Check model = new Check();
		model.setEchostr("aaabb");
		String s = validateService.genToken();// "", null
		return "Hello World:" + s;
	}

	@RequestMapping("/available")
	public @ResponseBody String available() {
		return "Hello World available";
	}

}
